/*
 * Copyright (c) 2016-2017 fulihui.com All right reserved
 * Project: information-core-170307
 * File name: RedisCategoryStatisticsDB.java
 */

package com.fulihui.information.core.redis;

import com.fulihui.information.core.db.CategoryStatisticsDB;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author Willard.Hu on 2017/2/16 0016.
 */
@Component("redisCategoryStatisticsDB")
public class RedisCategoryStatisticsDB implements CategoryStatisticsDB {
    private static final String KEY_PREFIX = "INFORMATION:CATEGORYSTATISTICSDB:";

    @Autowired
    private JedisPool jedisPool;

    /**
     * @see CategoryStatisticsDB#incr(String, StatisticType)
     */
    @Override
    public long incr(String categoryCode, StatisticType type) {
        String key = KEY_PREFIX + categoryCode;
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hincrBy(key, type.name(), 1);
        }
    }

    /**
     * @see CategoryStatisticsDB#reset(String)
     */
    @Override
    public boolean reset(String categoryCode) {
        String key = KEY_PREFIX + categoryCode;
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.del(key) > 0;
        }
    }

    /**
     * @see CategoryStatisticsDB#get(String, StatisticType)
     */
    @Override
    public long get(String categoryCode, StatisticType type) {
        String key = KEY_PREFIX + categoryCode;
        try (Jedis jedis = jedisPool.getResource()) {
            String value = jedis.hget(key, type.name());
            return StringUtil.isNotBlank(value) ? Long.parseLong(value) : 0;
        }
    }
}
